// 两种求平方根的算法
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX 0.001
// 二分法
float my_sqrt(float num)
{
    if (num < 0)
        return 0;
    float l = 0, h = num, m;
    m = l + (h - l) / 2;
    float r = m * m;
    while (abs(r - num) > MAX)
    {
        if (r > num)
        {
            h = m;
        }
        else
        {
            l = m;
        }
        m = l + (h - l) / 2;
        r = m * m;
    }
    return m;
}
// 牛顿迭代法
float my_sqrt2(float num)
{
    float x = 1;
    float r;
    do
    {
        x = (num / x + x) / 2.0;
        r = x * x - num;
    } while (abs(r) > MAX);
    return x;
}

int main()
{
    /*******************code*******************/
    float a = 2.0;
    printf("%.3f", my_sqrt2(a));

    /******************************************/
    fflush(stdin);

    printf("\n\n****************************\n");
    printf("Press Enter key to continue\n");
    getchar();
    return 0;
    /******************************************/
}
